package com.itheima.controller;

import com.itheima.pojo.Book;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@ResponseBody
@RequestMapping("book")

public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result findAll(){
        List<Book> books = bookService.findAll();
        Integer responseCode = books == null ? ResponseCode.FIND_ERR : ResponseCode.FIND_OK;
        String msg = books == null ? "数据查询失败,请重试" : "";
        return new Result(books,responseCode,msg);
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Integer id){
        Book book = bookService.findById(id);
        Integer responseCode = book == null ? ResponseCode.FIND_ERR : ResponseCode.FIND_OK;
        String msg = book == null ? "数据查询失败,请重试" : "";
        return new Result(book,responseCode,msg);
    }

    @PostMapping
    public Result addBook(@RequestBody Book book){
        boolean flag = bookService.addBook(book);
        return new Result( flag,flag ? ResponseCode.ADD_OK : ResponseCode.ADD_ERR );
    }

    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean flag = bookService.deleteById(id);
        return new Result( flag,flag ? ResponseCode.DELETE_OK : ResponseCode.DELETE_ERR );
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        boolean flag = bookService.updateBook(book);
        return new Result( flag,flag ? ResponseCode.UPDATE_OK : ResponseCode.UPDATE_ERR );
    }

}